'use strict';

const Controller = require('egg').Controller;

class JspangController extends Controller {
  async index() {

    const { ctx, app } = this;
    const username = ctx.session.username;
    console.log(ctx.session.counter);
    // 调用模板引擎, 1.文件名默认指向/app/view/jspang.html 2.给页面的参数
    await ctx.render('jspang.html', {
      newTime: app.currentTime(),
      newTimeProperty: app.timeProp,
      id: 2021,
      name: '小明',
      age: 20,
      username,
      skills: [ '态势按摩', '仅有错配', '水疗室怕' ],
    });
    // ctx.body = '<h1>我是😀</h1>';
  }

  // 异步方法 异步测试test 是否通过
  async getGirls() {
    const { ctx } = this;
    await new Promise(resolve => {
      setTimeout(() => {
        resolve(ctx.body = '<h1>小红正向你走来</h1>');
      }, 5000);
    });
  }

  // httpClient
  // get 自由传参模式，
  async getGirl() {
    const ctx = this.ctx;
    ctx.body = ctx.query;
  }
  // get 固定传参模式
  async getGirl2() {
    const ctx = this.ctx;
    ctx.body = 'getGril2 固定传参模式' + ctx.params.name + ctx.params.sex + ctx.params.list;
  }
  // post
  async add() {
    const ctx = this.ctx;
    // 接收参数
    ctx.body = {
      status: 200,
      data: ctx.request.body,
    };
  }

  // 调用service
  async getGirlService() {
    const { ctx } = this;
    const res = await ctx.service.jspangService.getGirl('899988');
    ctx.body = res;
  }

  // 处理 服务器cookie ,浏览器是不能获得的
  async addCookie() {
    const { ctx } = this;
    // 第三个参数 是个对象,maxAge cookie存在时间， httpOnly浏览器是否能获取cookie
    ctx.cookies.set('user', '中文', {
      maxAge: 1000 * 60,
      httpOnly: false,
      encrypt: true,
    });
    // 添加session
    ctx.session.username = '小红';
    ctx.body = {
      status: 200,
      data: '添加成功',
    };
  }
  async delCookie() {
    const { ctx } = this;
    ctx.cookies.set('user', null);
    ctx.session.username = null;
    ctx.body = {
      status: 200,
      data: '删除成功',
    };
  }
  async editorCookie() {
    const { ctx } = this;
    ctx.cookies.set('user', 'biliii');
    ctx.session.username = '小学生';
    ctx.body = {
      status: 200,
      data: '修改成功',
    };
  }
  async showCookie() {
    const { ctx } = this;
    const user = ctx.cookies.get('user', {
      encrypt: true,
    });

    ctx.body = {
      status: 200,
      data: '查看成功',
      valueCookie: user,
    };
  }


  // context 扩展
  async newContext() {
    const { ctx } = this;
    const param = ctx.params();
    console.log(param);
    ctx.body = 'newContext';
  }

  // request 扩展
  async newRequest() {
    const { ctx } = this;
    const token = ctx.request.token;
    ctx.body = {
      status: 200,
      token,
    };
  }
  //response 扩展
  async newReponse(){
    const {ctx} = this
    ctx.response.token = 'jspang'
    const testBase64 = ctx.helper.base64Encode('newReponse')
    ctx.body = testBase64 
  }
}
// 必须将JspangController 暴露出去，才能被发现
module.exports = JspangController;
